/*
 * author      : dormi330
 * date        : 2018/7/5
 * project     : mybatis
 * description : Controller 异常处理接口
 */

package com.deep.trade.adaptor.provided.rest;

import com.deep.trade.common.HttpResponsePayload;
import com.deep.trade.common.TradeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

    public static final int SYSTEM_ERROR_CODE = 500;

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private HttpResponseAssembler assembleService;

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<?> handler(Exception ex) {
        HttpResponsePayload payload;
        int code = (ex instanceof TradeException) ? ((TradeException) ex).getCode() : SYSTEM_ERROR_CODE;
        payload = assembleService.unhappy(code, ex.getMessage());
        return new ResponseEntity<>(payload, HttpStatus.valueOf(code));
    }
}
